var express = require('express');
var router = express.Router();
const UserModel = require("../../models/UserModel");
const md5 = require("md5");
router.get("/reg", (req, res) => {
  //响应 HTML 内容
  res.render("auth/reg");
});
router.post("/reg", (req, res) => {
  UserModel.create({ ...req.body, password: md5(req.body.password) }, (err, data) => {
    if (err) {
      res.status(500).send("注册失败~~");
      return;
    }
    //成功提醒
    res.render("success", { msg: "注册成功哦~~~", url: "/login" });
  });
});
router.get("/login", (req, res) => {
  //响应 HTML 内容
  res.render("auth/login");
});
router.post("/login", (req, res) => {
  let { username,password } = req.body;
  UserModel.findOne(
    { username: username, password: md5(password) },
    (err, data) => {
      if (err) {
        res.status(500).send("登录失败~~");
        return;
      }
      if(!data){
        return res.send('账号或密码错误');
      }
      // 写入session
      req.session.username = data.username;
      req.session._id = data._id;
      //成功提醒
      res.render("success", { msg: "登录成功哦~~~", url: "/account" });
    }
  );
});
// 如果用get,可能会出现csrf跨站请求伪造，post比较安全
router.post("/logout", (req, res) => {
  req.session.destroy(() => {
    res.render("success", { msg: "退出成功~~~", url: "/login" });
  });
});
module.exports = router;
